package zl.Util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static SessionFactory factory;
    static {
        factory = new Configuration().configure().buildSessionFactory();
    }

    // 线程局部变量
    private static ThreadLocal<Session> session = new ThreadLocal<>();

    /**
     * 打开session，尽可能复用
     * 	1) 先从线程内部有没有该对象
     * 	2) 从factory获得session，并放到线程内部
     * */
    public static Session openSession() {
        Session s = session.get();	//从线程变量中获得值
        if(s==null || !s.isOpen()) {
            s = factory.openSession();
            session.set(s);
        }
        return s;
    }

    /**
     * 关闭线程中的session
     * */
    public static void closeSession() {
        Session s = session.get();
        session.set(null);

        if(s!=null && s.isOpen()) {
            s.close();
        }
    }

    /**
     * 关闭sessionFactory
     * */
    public static void destory() {
        if(factory.isOpen()) {
            factory.close();
        }
    }
}
